﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using YAWD.BL.Providers;
using YAWD.BL.Services;
using YAWD.Utils;
using System.IO;
using YAWD.Properties;
using System.Collections.Generic;

namespace YAWD.UserControls
{
    /// <summary>
    /// Interaction logic for ucProvider.xaml
    /// </summary>
    public partial class UcProvider : INotifyPropertyChanged
    {
        public bool GetAll { private get; set; }
        public bool IsExpanded { private get; set; }

        private Providers _providerName;
        private IProvider _provider;
        private readonly string _initPath = string.Empty;
        private readonly BackgroundWorker _backgroundActivity = new BackgroundWorker();
        private BackgroundWorker _updateWorker;

        public UcProvider()
        {
            Settings settings = Settings.Default;
            if (string.IsNullOrWhiteSpace(settings.WallPapersPath))
                _initPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            else
                _initPath = settings.WallPapersPath;

            InitializeComponent();
            _backgroundActivity.DoWork += _backgroundActivity_DoWork;
        }

        void provider_ProgressChanged(object sender, EventArgs e)
        {
            OnPropertyChanged("pbarCurrent");
        }
        public double PbarCurrent
        {
            get
            {
                if (this._provider != null)
                    return this._provider.Current;
                
                return 0;
            }
        }
        void provider_CurrentImageChanged(object sender, EventArgs e)
        {
            OnPropertyChanged("lblCurrentImage");
        }
        public string lblCurrentImage
        {
            get
            {
                if (this._provider != null)
                    if (string.IsNullOrWhiteSpace(this._provider.CurrentImage))
                        return _provider.LastDwImage;
                    else
                        return this._provider.CurrentImage;
                
                return string.Empty;
            }
        }
        void provider_ImagesChanged(object sender, EventArgs e)
        {
            OnPropertyChanged("lstImages");
        }
        public IList<string> lstImages
        {
            get
            {
                if (this._provider != null)
                    if (this.IsExpanded == true)
                    {
                        if (this._provider.Images != null)
                            return this._provider.Images;
                        else
                            return Util.LoadImage(_providerName, _initPath);
                    }
                    else
                        return new List<string>();
                else
                    return new List<string>();
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (GetAll == false)
                btnGetAll.Visibility = Visibility.Collapsed;

            _providerName = (Providers)Enum.Parse(typeof(Providers), this.Name);
            Type type = Type.GetType("YAWD.BL.Providers." + _providerName.ToString());
            if (type != null)
            {
                _provider = (IProvider) Activator.CreateInstance(type);
                if (_provider != null)
                {
                    _provider.Init();
                    this._provider.ProgressChanged += new EventHandler(provider_ProgressChanged);
                    this._provider.CurrentImageChanged += new EventHandler(provider_CurrentImageChanged);
                    this._provider.ImagesChanged += new EventHandler(provider_ImagesChanged);
                    this._provider.CurrentImage = _provider.LastDwImage;
                    this.lblLastUpdated.Text = this._provider.LastUpdated.ToString("d");
                    this.lblUrl.Text = this._provider.URL;
                    OnPropertyChanged("lblCurrentImage");
                    TxtHeader.Text = _providerName.ToString().ToUpperInvariant();
                    ExpExpander.IsExpanded = IsExpanded;
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        private void btnGetAll_Click(object sender, RoutedEventArgs e)
        {
            if (new YAWD.Windows.MessageBoxYesNo("Do you really want to get all the image ?", true, false).ShowDialog() == true)
            {
                try
                {
                    _backgroundActivity.RunWorkerAsync(_providerName.ToString());
                }
                catch (Exception)
                { }

                ShowProgressBar();

                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += new DoWorkEventHandler(worker_DoWork);
                worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
                worker.RunWorkerAsync();
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            HideProgressbar();
        }

        private void HideProgressbar()
        {
            progressBar.Visibility = Visibility.Collapsed;
            btnCancel.Visibility = Visibility.Collapsed;
            if (GetAll == true)
                btnGetAll.Visibility = Visibility.Visible;
            btnUpdate.Visibility = Visibility.Visible;
            this._provider.Current = 0;
            this.lblLastUpdated.Text = this._provider.LastUpdated.ToString("d");
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            _provider.getAll();
        }
        void _backgroundActivity_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                string strActivity = e.Argument.ToString();
                if (string.IsNullOrWhiteSpace(strActivity) == false)
                   Util.NotifyEvent(strActivity);

            }
            catch (Exception)
            { }
        }


        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            Update();
        }

        public void Update()
        {
            if (_updateWorker == null)
            {
                try
                {
                    _backgroundActivity.RunWorkerAsync(_providerName.ToString());
                }
                catch (Exception)
                { }

                ShowProgressBar();

                _updateWorker = new BackgroundWorker();
                _updateWorker.DoWork += new DoWorkEventHandler(updateWorker_DoWork);
                _updateWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(updateWorker_RunWorkerCompleted);
                _updateWorker.RunWorkerAsync();
            }
        }

        private void ShowProgressBar()
        {
            progressBar.Visibility = Visibility.Visible;
            btnCancel.Visibility = Visibility.Visible;
            btnGetAll.Visibility = Visibility.Collapsed;
            btnUpdate.Visibility = Visibility.Collapsed;
            this._provider.Current = 0;
        }

        void updateWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            HideProgressbar();
            _updateWorker = null;
        }

        void updateWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            _provider.update();
        }

        void OnSetWallPaper(object sender, ExecutedRoutedEventArgs args)
        {
            Util.ChangeWallPaper(args.Parameter.ToString());
        }
        void OnExclude(object sender, ExecutedRoutedEventArgs args)
        {
            WallPaperServices.addExcludeWallPaper(args.Parameter.ToString());
        }
        void OnDelete(object sender, ExecutedRoutedEventArgs args)
        {
            File.Delete(args.Parameter.ToString());
            this._provider.Images = Util.LoadImage(_providerName, _initPath);
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            HideProgressbar();

            _provider.CancelAsync();
            if (_updateWorker != null)
                _updateWorker = null;
        }

        private void Expander_Expanded(object sender, RoutedEventArgs e)
        {
            this.IsExpanded = true;
            if (this._provider != null)
                this._provider.Images = Util.LoadImage(_providerName, _initPath);
        }

        private void Expander_Collapsed(object sender, RoutedEventArgs e)
        {
            this.IsExpanded = false;
            if (this._provider != null)
                if (this._provider.Images != null)
                    OnPropertyChanged("lstImages");
        }
    }
}
